

import axios, { type InternalAxiosRequestConfig, type AxiosError, type AxiosRequestConfig } from 'axios'


//!创建 Axios实例
const instance = axios.create({
  timeout: 2000,
});

//!http request 请求拦截器----request.use: 请求前的拦截逻辑
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  //设置请求头
  config.headers.set('Content-Type', 'application/json');
  if (config.method == 'post') {
    config.data = JSON.stringify(config.data)
  };
  return config;
}, (error: AxiosError) => {
  Promise.reject(error);
});





//!http response 响应拦截器----response.use: 响应后的拦截逻辑
instance.interceptors.response.use((response) => {
  return response.status == 200 ? Promise.resolve(response) : Promise.reject(response);
}, (error) => {
  const { response } = error;
  errorHanld(response.status, response.info);
});

//!失败状态码
const errorHanld = (status: number, info: string) => {
  switch (status) {
    case 400:
      console.log('语义有误');
      break;
    case 401:
      console.log('服务器认证');
      window.location.href = '/login'; //如果是401，可能是未授权，跳转到登录页
      break;
    case 402:
      console.log('服务器拒绝访问');
      break;
    case 403:
      console.log('地址有误');
      break;
    case 500:
      console.log('服务器遇到意外');
      break;
    case 502:
      console.log('服务器无法响应');
      break;
    default:
      console.log(info);
      break;
  }
};


export default instance;
